package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.constant.MessageConstant;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.yaml.snakeyaml.events.Event;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询店铺类型
     * @return
     */
    @Override
    public Result queryTypeList() {
        //不存在缓存穿透的问题
        //前端并没有传递id，所以这里不需要判断id是否为空
        //用户无法恶意通过id查询不存在的店铺类型来导致数据库访问压力过大

        //从redis中查询店铺类型
        String shopTypeKey = RedisConstants.CACHE_SHOP_TYPE_KEY + "type";
        String shopTypeJson = stringRedisTemplate.opsForValue().get(shopTypeKey);

        List<ShopType> shopTypes = null;
        //存在直接返回
        if (shopTypeJson != null) {
            if(!StringUtils.isEmpty(shopTypeJson)){
                shopTypes = JSONUtil.toList(shopTypeJson, ShopType.class);
                return Result.success(shopTypes);
            }else {
                //解决缓存穿透问题
                //返回错误信息
                //return Result.error(MessageConstant.SHOPTYPE_IS_NOT_EXISTS);
            }
        }
        //不存在，查询数据库
        shopTypes = query().orderByAsc("sort").list();
        //不存在，返回错误
        if (shopTypes == null) {
            //解决缓存穿透问题
            //设置redis空串
            //stringRedisTemplate.opsForValue().set(shopTypeKey, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return Result.error(MessageConstant.SHOPTYPE_IS_NOT_EXISTS);
        }
        //存在，保存redis
        stringRedisTemplate.opsForValue().set(shopTypeKey, JSONUtil.toJsonStr(shopTypes),
                RedisConstants.CACHE_SHOP_TYPE_TTL, TimeUnit.DAYS);
        //返回
        return Result.success(shopTypes);
    }
}
